package util.lambda;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhanglinfeng
 * @date create in 2023/1/30 14:17
 */
public abstract class BaseFieldCompletion<T, U> {
    private final List<T> dataList;
    private final List<BiConsumer<T, U>> setList = new ArrayList<>();
    private final Function<T, Object> get;

    public BaseFieldCompletion(List<T> dataList, Function<T, Object> get) {
        this.dataList = dataList;
        this.get = get;
    }

    public final BaseFieldCompletion<T, U> then(BiConsumer<T, U> set) {
        setList.add(set);
        return this;
    }

    public final void deal() {
        Map<String, U> dataMap = Empty.of(dataList.stream().map(get).filter(Objects::nonNull).map(String::valueOf).distinct().collect(Collectors.joining(","))).map(this::getMap).orElse(null);
        if (null == dataMap || dataMap.isEmpty()) {
            return;
        }
        for (T t : dataList) {
            Optional.ofNullable(get.apply(t)).map(String::valueOf).map(dataMap::get).ifPresent(obj -> setList.forEach(set -> set.accept(t, obj)));
        }
    }

    /**
     * 获取数据
     *
     * @param ids ids
     * @return Map<String, U>
     */
    protected abstract Map<String, U> getMap(String ids);

}
